package com.example.sensors;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.example.priorityobserver.Observable;

public abstract class AbstractSensor extends Observable<Map<String, Object>>
		implements ISensor {

	protected boolean isSensorEnabled = false;
	Map<String, Object> lastEventArgs = null;

	public void OnSensorChanged(Map<String, Object> eventArgs) {
		if (lastEventArgs == null || !isEquals(eventArgs, lastEventArgs)) {
			lastEventArgs = eventArgs;
			notifyObservers(eventArgs);
		}
	}

	protected boolean isEquals(Map<String, Object> eventArgs0,
			Map<String, Object> eventArgs1) {
		Iterator<Entry<String, Object>> it = eventArgs0.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, Object> current = it.next();
			if (!eventArgs1.containsKey(current.getKey())
					|| !eventArgs1.get(current.getKey()).equals(
							current.getValue()))
				return false;
		}
		return true;
	}

	public Map<String, Object> initEventArgs() {
		Map<String, Object> eventArgs = new LinkedHashMap<String, Object>();
		eventArgs.put("class", this.getClass().getCanonicalName());
		eventArgs.put("sensorName", getSensorName());
		return eventArgs;
	}

	public void disableSensor() {
		isSensorEnabled = false;
		Map<String, Object> eventArgs = initEventArgs();
		eventArgs.put("eventType", "sensorActivityChange");
		eventArgs.put("sensorFunctionality", "OFF");
		OnSensorChanged(eventArgs);
	}

	public void enableSensor() {
		isSensorEnabled = true;
		Map<String, Object> eventArgs = initEventArgs();
		eventArgs.put("eventType", "sensorActivityChange");
		eventArgs.put("sensorFunctionality", "ON");
		OnSensorChanged(eventArgs);
	}

	public void setSensorParameters(Map<String, Object> parameters) {
	}
}
